package com.dimples.dd.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dimples.dd.common.constant.DDServerConstant;
import com.dimples.dd.common.model.DDAuthUser;
import com.dimples.dd.common.model.Option;
import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.common.result.CommonResult;
import com.dimples.dd.log.core.annotation.ApiLog;
import com.dimples.dd.log.core.enums.OperateTypeEnum;
import com.dimples.dd.system.model.form.UserForm;
import com.dimples.dd.system.model.query.UserPageQuery;
import com.dimples.dd.system.model.vo.UserInfoVO;
import com.dimples.dd.system.model.vo.UserPageVO;
import com.dimples.dd.system.model.vo.UserSimpleVO;
import com.dimples.dd.system.service.SystemUsersService;
import com.dimples.dd.web.core.annotation.PreventDuplicateResubmit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/6/13
 */
@Tag(name = "01.用户接口")
@Validated
@RestController
@RequestMapping("users")
@RequiredArgsConstructor
public class SysUserController {

    private final SystemUsersService userService;

    @Operation(summary = "用户分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('system:user:query')")
    @ApiLog(operateType = OperateTypeEnum.SELECT, applicationName = DDServerConstant.DD_SERVER_SYSTEM)
    public PageResult<UserPageVO> getUserPage(
            @ParameterObject UserPageQuery queryParams
    ) {
        IPage<UserPageVO> result = this.userService.getUserPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "获取用户下拉选项-带分页")
    @GetMapping("/options")
    @PreAuthorize("@ss.hasPerm('system:user:query')")
    public PageResult<Option<Long>> listUserOptions(UserPageQuery userPageQuery) {
        return this.userService.listUserOptions(userPageQuery);
    }

    @Operation(summary = "用户表单数据")
    @GetMapping("/{userId}/form")
    @PreAuthorize("@ss.hasPerm('system:user:query')")
    @ApiLog(operateType = OperateTypeEnum.SELECT, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<UserForm> getUserForm(
            @Parameter(description = "用户ID") @PathVariable Long userId
    ) {
        UserForm formData = userService.getUserFormData(userId);
        return CommonResult.success(formData);
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('system:user:create')")
    @PreventDuplicateResubmit
    @ApiLog(operateType = OperateTypeEnum.CREATE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Boolean> createUser(
            @RequestBody @Valid UserForm userForm
    ) {
        this.userService.createUser(userForm);
        return CommonResult.success(true);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/{userId}")
    @PreAuthorize("@ss.hasPerm('system:user:update')")
    @ApiLog(operateType = OperateTypeEnum.UPDATE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Boolean> updateUser(
            @Parameter(description = "用户ID") @NotNull(message = "不能为空") @PathVariable Long userId,
            @RequestBody @Valid UserForm userForm) {
        userForm.setId(userId);
        this.userService.updateUser(userForm);
        return CommonResult.success(true);
    }

    @PatchMapping("/{userId}/password")
    @Operation(summary = "重置用户密码")
    @PreAuthorize("@ss.hasPerm('system:user:update-password')")
    @ApiLog(operateType = OperateTypeEnum.UPDATE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Boolean> updateUserPassword(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestBody String password
    ) {
        this.userService.updateUserPassword(userId, password);
        return CommonResult.success(true);
    }

    @Operation(summary = "修改用户状态")
    @PatchMapping(value = "/{userId}/status")
    @PreAuthorize("@ss.hasPerm('system:user:update')")
    @ApiLog(operateType = OperateTypeEnum.UPDATE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Boolean> updateUserStatus(
            @Parameter(description = "用户ID") @PathVariable Long userId
    ) {
        return CommonResult.success(userService.updateUserStatus(userId));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('system:user:delete')")
    @ApiLog(operateType = OperateTypeEnum.DELETE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Boolean> deleteUsers(
            @Parameter(description = "用户ID，多个以英文逗号(,)分割") @NotBlank(message = "不能为空") @PathVariable String ids
    ) {
        this.userService.deleteUsers(StrUtil.splitToArray(ids, StrUtil.COMMA));
        return CommonResult.success(true);
    }

    @Operation(summary = "获取用户认证信息", hidden = true)
    @GetMapping("/{username}/authInfo")
    public CommonResult<DDAuthUser> getUserAuthUser(
            @Parameter(description = "用户名") @PathVariable String username
    ) {
        DDAuthUser authUser = this.userService.getUserAuthUser(username);
        return CommonResult.success(authUser);
    }

    @Operation(summary = "获取登录用户信息")
    @GetMapping("/me")
    public CommonResult<UserInfoVO> getCurrentUserInfo() {
        UserInfoVO userInfoVO = userService.getCurrentUserInfo();
        return CommonResult.success(userInfoVO);
    }

    @GetMapping({ "simple-list"})
    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    @PreAuthorize("@ss.hasPerm('system:user:query')")
    public CommonResult<List<UserSimpleVO>> getSimpleUserList() {
        List<UserSimpleVO> result = this.userService.getSimpleUserList();
        return CommonResult.success(result);
    }

    @PutMapping(value = "login/{userId}")
    @Operation(summary = "更新最后登录时间")
    public CommonResult<Boolean> updateUserLogin(
            @Parameter(description = "用户ID") @NotNull(message = "不能为空") @PathVariable Long userId,
            @RequestParam(value = "loginIp") String loginIp
    ) {
        this.userService.updateUserLogin(userId, loginIp);
        return CommonResult.success(true);
    }
}
